//材质属性side：
//THREE.FrontSide  前面渲染，默认
// THREE.BackSide 背面渲染
// THREE.DoubleSide 双面渲染

import { useEffect } from 'react';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';

function SimpleCubeWithLight() {
  useEffect(() => {
    // 1. 初始化场景、相机、渲染器
    const scene = new THREE.Scene();
    scene.background = new THREE.Color('white');

    const fov = 75;
    const aspect = 2; // the canvas default
    const near = 0.1;
    const far = 25;
    const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
    camera.position.z = 5;
    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    // 轨道控制器
    const controls = new OrbitControls(camera, renderer.domElement);

    // 物体
    const planeWidth = 1;
    const planeHeight = 1;
    const geometry = new THREE.PlaneGeometry(planeWidth, planeHeight);

    const loader = new THREE.TextureLoader();

    // function makeInstance(geometry, color, rotY, url) {
    //   const texture = loader.load(url, renderer);
    //   const material = new THREE.MeshPhongMaterial({
    //     color,
    //     map: texture,
    //     opacity: 0.5,
    //     transparent: true,
    //     side: THREE.DoubleSide,
    //   });

    //   const mesh = new THREE.Mesh(geometry, material);
    //   scene.add(mesh);

    //   mesh.rotation.y = rotY;
    // }
    function makeInstance(geometry, color, rotY, url) {
      // 创建一个父容器
      const base = new THREE.Object3D();
      scene.add(base);
      base.rotation.y = rotY;

      // 循环创建两个子网格，分别传入 x = -1 和 x = 1，用于控制子网格的位置和纹理偏移
      [-1, 1].forEach((x) => {
        const texture = loader.load(url, renderer); // 加载纹理
        texture.offset.x = x < 0 ? 0 : 0.5; // 左侧网格（x=-1）偏移量为0，右侧为0.5
        texture.repeat.x = 0.5; // 将纹理在 X 轴上重复比例设为 0.5，即只显示一半宽度
        const material = new THREE.MeshPhongMaterial({
          color,
          map: texture, // 应用纹理
          opacity: 0.5,
          transparent: true,
          side: THREE.DoubleSide,
        });

        const mesh = new THREE.Mesh(geometry, material);
        base.add(mesh);

        mesh.position.x = x * 0.5;
      });
    }

    makeInstance(geometry, 'pink', 0, '/noData.png');
    makeInstance(geometry, 'lightblue', Math.PI * 0.5, '/noData.png');
    // 光源
    function addLight(...pos) {
      const color = 0xffffff;
      const intensity = 1;
      const light = new THREE.DirectionalLight(color, intensity);
      light.position.set(...pos);
      scene.add(light);
    }
    addLight(-1, 2, 4);
    addLight(1, -1, -2);

    // 5. 渲染循环
    function animate() {
      requestAnimationFrame(animate);
      renderer.render(scene, camera);
    }
    animate();

    // 清理函数
    return () => {
      document.body.removeChild(renderer.domElement);
    };
  }, []);

  return <div />;
}

export default SimpleCubeWithLight;
